/*
 * Create:      柿子
 * CreateDate:  2022/08/30
 * Describe：   单表操作 - 单表查询/单表增删改查
 * */
import React, { Component } from 'react';
import { Spin, Row, Col, Button, Divider, Popconfirm, message, Icon } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import PublicModalQueryTable from 'pages/common/PublicModalQueryTable';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import PublicTableEditable from 'pages/common/PublicTableEditable';
import CommonPagination from 'components/pagination/index';
import './style/index.less';

class SingleTableOperation extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      userData,
      selectData: {},
      categoryData: {},
      page: 1,
      pageSize: 10,
      columns: [],
      queryFormData: [],
      totalWidth: 2590,
      tableData: [],
      loading: false,
      total: 0,
      rowData: {},
      formData: [],
      clientQueryHeight: 0,
      rowID: ''
    }
  }

  componentDidMount() {
    let newCategory;
    if ('paras' in this.props && this.props.paras && this.props.paras.params) { // 侧菜单获取类别参数
      newCategory = this.props.paras.params;
    } else {
      if ('location' in this.props && this.props.location.state && this.props.location.state.params) { // 头菜单获取类别参数
        newCategory = this.props.location.state.params;
        React.$setSessionData('SingleTableOperation', newCategory, false);
      } else { // 头菜单刷新界面时获取类别
        newCategory = React.$getSessionData('SingleTableOperation', false);
      }
    }
    let categoryData = Util.getObjByUrlStr(newCategory);
    console.log('SingleTableOperation', categoryData);
    let defaultPageSize = categoryData?.paginationSize === 'small' ? (categoryData?.defaultPageSize || 10) : (categoryData?.defaultPageSize || 50); // 默认条数
    let defaultDetailPageSize = categoryData?.detailPaginationSize === 'small' ? (categoryData?.defaultDetailPageSize || 10) : (categoryData?.defaultDetailPageSize || 50); // 明细列表默认条数
    this.setState({ categoryData, spinLoading: true, pageSize: defaultPageSize, detailPageSize: defaultDetailPageSize }, () => {
      this.getSelectData();
      categoryData?.addDataListSelectionFlag !== 'Y' && this.getFormData();
    });
  }

  componentWillUnmount() {
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state, callback) => { return; }
  }

  // 获取下拉框数据
  getSelectData = async () => {
    try {
      let { userData, categoryData } = this.state;
      if (!categoryData?.selectCode) {
        this.getColumnsData();
        return;
      };
      let data = {
        params: [{
          createType: categoryData?.groupType || '',
          groupType: categoryData?.groupType || '',
          hospID: userData?.hospID || ''
        }]
      }
      let res = await React.$asyncPost(this, categoryData?.selectCode, data);
      let selectData = res && 'result' in res && Object.prototype.toString.call(res.result) === '[object Object]' ? res.result : res;
      this.setState({ selectData }, () => {
        this.getColumnsData();
      });
    } catch (error) {
      console.log(error);
      this.getColumnsData();
    }
  }

  // 获取表头数据
  getColumnsData = async () => {
    try {
      const { categoryData, selectData } = this.state;
      if (!categoryData?.componentName) {
        this.setState({ spinLoading: false });
        return;
      };
      let data = {
        params: [{
          type: 'C',
          compontName: categoryData?.componentName,
          reactCode: [categoryData?.componentName],
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let nColumns = res.result?.C || [];
      if (nColumns && nColumns.length > 0) {
        for (let i = 0; i < nColumns.length; i++) {
          let currentRecord = nColumns[i];
          nColumns[i].editable = !!(currentRecord?.linkMethod);
          nColumns[i].inputType = currentRecord?.linkMethod || '';
          nColumns[i].detailitem = currentRecord?.linkService && currentRecord?.linkService in selectData ? selectData[currentRecord?.linkService] : [];
        }
        this.setState({ columns: nColumns, totalWidth: res.totalWidth });
      }
      let nFormData = JSON.parse(JSON.stringify(res.result?.formData || []));
      this.setState({ queryFormData: nFormData, spinLoading: false }, () => {
        if (nFormData && nFormData.length > 0) {
          let clientQueryDom = document.getElementById('dc-header-query');
          this.setState({ clientQueryHeight: clientQueryDom?.clientHeight || 64 });
        }
        this.getTableData('N');
      });
    } catch (error) {
      this.setState({ spinLoading: false });
    }
  }

  // 获取表单数据
  getFormData = async () => {
    try {
      const { categoryData } = this.state;
      let formName = categoryData?.componentNameForm || categoryData?.componentName + 'Form';
      if (!formName) return;
      let data = {
        params: [{
          type: 'C',
          compontName: formName,
          reactCode: [formName],
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      this.setState({ formData: res.result?.formData || [] });
    } catch (error) {
      console.log(error);
    }
  }

  // 查询
  handleQuery = (isTips) => {
    this.setState({ page: 1 }, () => {
      this.getTableData(isTips);
    })
  }

  // 获取表格数据
  getTableData = async (isTips) => {
    try {
      const { categoryData, page, pageSize } = this.state;
      if (!categoryData?.queryCode) return;
      let values = await this.formRef.handleSave();
      if (values.error) {
        message.error('请完善必填信息');
        return;
      }
      this.setState({ loading: true }); // 分页loading
      let data = {
        params: [{
          createType: categoryData?.groupType || '',
          groupType: categoryData?.groupType || '',
          ...values,
          error: undefined
        }]
      };
      if (categoryData?.hidePaginationFlag !== 'Y') { // 是否需要分页
        data.pagination = [{
          pageSize,
          currentPage: page,
          sortColumn: 'Code',
          sortOrder: 'asc'
        }];
      }
      let res = await React.$asyncPost(this, categoryData?.queryCode, data);
      let tableData = res.result?.rows || res.result?.data || res.result?.Data || [];
      for (var i = 0; i < tableData.length; i++) {
        let currentRecord = tableData[i];
        tableData[i].key = currentRecord[categoryData?.idIndex || 'id'] || i;
      }
      this.setState({ tableData, total: res.result?.total || res.result?.TotalCount || 0, loading: false }, () => {
        categoryData?.inlineEditingFlag === 'Y' && this.editableRef && this.editableRef.getTableData(tableData);
        isTips !== 'N' && this.state.total < 1 ? message.error('未查询到相关数据！') : '';
      });
    } catch (error) {
      console.log(error);
      this.setState({ tableData: [], total: 0, loading: false });
    }
  }

  // 提供修改page和pageSize的回调函数
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 新增
  handleAdd = () => {
    let { rowData, categoryData } = this.state;
    if (categoryData?.addDataListSelectionFlag === 'Y') { // 新增列表样式
      this.modalListRef && this.modalListRef.modifyVisible(true);
    } else if (categoryData?.inlineEditingFlag === 'Y' && categoryData?.addInlineEditingFlag === 'Y') { // 行内编辑新增
      this.editableRef && this.editableRef.handleAddTableData();
    } else {
      let idIndex = categoryData?.idIndex || 'id';
      if (rowData && idIndex in rowData && rowData[idIndex]) {
        this.setState({ rowData: {} })
      }
      this.modalFormRef && this.modalFormRef.modifyVisible(true);
    }
  }

  // 编辑
  handleModify = record => {
    this.setState({ rowData: record }, () => {
      this.modalFormRef && this.modalFormRef.modifyVisible(true);
    })
  }

  // 删除
  handleDelete = async (record) => {
    try {
      const { categoryData } = this.state;
      let idIndex = categoryData?.idIndex || 'id';
      if (!(record && record[idIndex]) || !categoryData?.deleteCode) return;
      let data = {
        params: [{
          createType: categoryData?.groupType || '',
          groupType: categoryData?.groupType || '',
          [idIndex]: record[idIndex]
        }]
      }
      let res = await React.$asyncPost(this, categoryData?.deleteCode, data);
      message.success(res.errorMessage ? res.errorMessage : '删除成功');
      // 刷新列表数据
      this.getTableData('N');
    } catch (error) {
      console.log(error);
    }
  }

  // 记录价格信息表单的值
  handleRecordFormInput = record => {
    let { rowData } = this.state;
    this.setState({ rowData: { ...rowData, ...record } });
  }

  // 保存
  handleSave = async (values) => {
    try {
      const { categoryData, rowData, userData } = this.state;
      let idIndex = categoryData?.idIndex || 'id';
      let saveCode = categoryData?.editCode ? categoryData?.editCode : categoryData?.addCode; // 当为编辑并且编辑代码存在的时候取editCode，正常新增编辑同一个接口取addCode
      if (!idIndex || !saveCode) {
        message.error('保存异常，请核对是否维护新增/修改代码！');
        return;
      };
      let data = {
        params: [{
          ...rowData,
          UpdateUserDr: userData?.userID || '',
          userID: userData?.userID || '',
          createType: categoryData?.groupType || '',
          groupType: categoryData?.groupType || '',
          ...values,
          error: undefined,
        }]
      }
      let res = await React.$asyncPost(this, saveCode, data);
      message.success(res.errorMessage ? res.errorMessage : (rowData[idIndex] ? '修改成功' : '保存成功'));
      this.modalFormRef && this.modalFormRef.modifyVisible(false, 'Y');
      this.setState({ rowData: {} }, () => {
        this.getTableData('N');
      });
    } catch (error) {
      console.log(error)
    }
  }

  // 操作行
  onClickRowPublic = (record) => {
    const { categoryData } = this.state;
    let idIndex = categoryData?.idIndex || 'id';
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== (record && idIndex in record ? record[idIndex] : record.key)))) {
          this.setState({ rowID: (record && idIndex in record ? record[idIndex] : record.key), rowData: record })
        } else {
          this.setState({ rowID: '' });
        }
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    const { categoryData } = this.state;
    let idIndex = categoryData?.idIndex || 'id';
    return categoryData?.isRowClick === 'Y' && (record && idIndex in record ? record[idIndex] : record.key) === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 获取form表单连带的操作按钮
  getFormBtn = () => {
    const { categoryData } = this.state;
    let btnArr = [{
      col: 1,
      title: '查询',
      typeCode: 'Button',
      type: 'primary',
      marginBottom: 12,
      onClick: this.handleQuery,
    }];
    if (categoryData?.addCode && categoryData?.addFollowQueryFlag === 'Y') {
      btnArr.push({
        col: 1,
        title: categoryData?.addBtnTitle || '新增',
        icon: 'plus',
        typeCode: 'Button',
        className: 'add-btn add-btn-noHover',
        marginLeft: 10,
        marginBottom: 12,
        onClick: this.handleAdd,
      })
    }
    return btnArr;
  }

  render() {
    let { spinLoading, categoryData, queryFormData, tableData, total, page, loading, totalWidth, columns, rowData, formData, clientQueryHeight, selectData } = this.state;
    let nQueryFormData = queryFormData && queryFormData.length > 0 ? [...queryFormData, ...this.getFormBtn()] : [];
    let operationWidth = (categoryData?.editCode) && categoryData?.deleteCode ? 130 : (categoryData?.editCode || categoryData?.deleteCode ? 80 : 0)
    let operationObj = {
      width: operationWidth,
      title: '操作',
      fixed: categoryData?.operationFixedFlag === 'Y' ? 'right' : null,
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <span>
          {(categoryData?.addCode && categoryData?.notEditableFlag !== 'Y') || categoryData?.editCode ? (
            <>
              <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
              <span className="span" onClick={() => this.handleModify(record)}>编辑</span>
            </>
          ) : ''}
          {/* 分割线 */}
          {categoryData?.deleteCode ? (
            <>
              <Divider type="vertical" />
              <Icon type="delete" className="common-record-delete-span"></Icon>
              <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
                <span className="span common-record-delete-span">删除</span>
              </Popconfirm>
            </>
          ) : ''}
        </span>
      ),
    }
    return (
      <Spin tip="资源加载中..." spinning={spinLoading}>
        <div className="dynamic-component">
          <Row id="dc-header-query" style={{ padding: '14px 24px 0 12px' }}>
            <Col span={20}>
              <DynamicRenderingForm
                className="dynamic-component-form"
                onRef={ref => this.formRef = ref}
                formItemCol={{ labelCol: 8, wrapperCol: 15 }}
                selectData={selectData}
                rowData={{}}
                formData={nQueryFormData && nQueryFormData.map((item => {
                  return {
                    ...item,
                    onPressEnter: item.typeCode === 'Input' || item.typeCode === 'InputNumber' || item.typeCode === 'TextArea' ? this.handleQuery : ''
                  }
                }))}
              />
            </Col>
            <Col span={4} style={{ textAlign: 'right' }}>
              {categoryData?.addCode && categoryData?.addFollowQueryFlag !== 'Y' ? (
                <Button icon="plus" className="add-btn add-btn-noHover" onClick={this.handleAdd}>{categoryData?.addBtnTitle || '新增'}</Button>
              ) : ''}
            </Col>
          </Row>
          <div className="common-query-split-line"></div>
          <div style={{ padding: 24 }} className="table-body-height">
            {categoryData?.inlineEditingFlag === 'Y' ? (
              <>
                <PublicTableEditable
                  loading={loading}
                  statusFlag={categoryData?.statusFlag || 'N'}
                  revertFlag={categoryData?.revertFlag || 'N'}
                  operationFlag={categoryData?.operationFlag || 'Y'}
                  deleteCode={categoryData?.deleteCode || ''}
                  isDelete={categoryData?.deleteCode ? 'Y' : 'N'}
                  recordID={categoryData?.idIndex || 'id'}
                  maxHeight={store.getState().tableHeight.y + 96 - clientQueryHeight}
                  totalWidth={totalWidth}
                  columns={columns}
                  componentName={categoryData?.componentName || ''}
                  handleRowSave={this.handleSave}
                  handleRowClick={this.onClickRowPublic}
                  getColumns={this.getColumnsData}
                  onRef={ref => this.editableRef = ref}
                />
                {categoryData?.hidePaginationFlag !== 'Y' ? (
                  <CommonPagination
                    complete={true}
                    size={categoryData?.paginationSize || 'small'}
                    current={page}
                    total={total}
                    search={'search'}
                    onShowSizeChange={(page, pageSize) => this.compilePage(1, pageSize)}
                    dataSource={tableData}
                    loading={loading}
                    onChange={this.compilePage}
                    pageSize={categoryData?.defaultPageSize || ''}
                  />
                ) : ''}
              </>
            ) : (
              <PublicTablePagination
                param={{
                  total: categoryData?.hidePaginationFlag !== 'Y' ? total : '', // 数据总条数
                  page: categoryData?.hidePaginationFlag !== 'Y' ? page : '', // 当前页数
                  loading,
                  pageSize: categoryData?.defaultPageSize || '',
                  size: categoryData?.paginationSize || 'small',
                  data: tableData, // 表格数据
                  x: totalWidth, // 表格的宽度
                  y: store.getState().tableHeight.y + 96 - clientQueryHeight,
                  height: store.getState().tableHeight.y + 146 - clientQueryHeight + 'px',
                  componentName: categoryData?.componentName || '',
                  columns: columns && columns.length > 0 ? (operationWidth ? [...columns, operationObj] : columns) : [], 	// 表头配置
                }}
                compilePage={this.compilePage}
                getColumns={this.getColumnsData}
                onClickRowPublic={this.onClickRowPublic}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            )}
          </div>

          {categoryData?.addDataListSelectionFlag !== 'Y' ? (
            <PublicModalFormHooks
              width={1000}
              rowData={rowData}
              formData={formData}
              selectData={selectData}
              onRef={ref => this.modalFormRef = ref}
              idField={categoryData?.idIndex || 'id'}
              handleSave={this.handleSave}
              recordFormInput={this.handleRecordFormInput}
            />
          ) : (
            <PublicModalQueryTable
              width="70vw"
              title={categoryData?.modalTitle || '从列表选择'}
              queryCode={categoryData?.modalQueryCode || ''}
              componentName={categoryData?.modalListComponentName || ''}
              paginationFlag={categoryData?.modalListPaginationFlag || ''}
              multipleFlag={categoryData?.modalListMultipleFlag || ''}
              idIndex={categoryData?.modalListIDIndex || ''}
              onRef={ref => this.modalListRef = ref}
              handleOk={this.handleSave}
            />
          )}
        </div>
      </Spin>
    )
  }
};

export default SingleTableOperation;

// 菜单管理配置参数示例 - params=interfaceType:singleTable&componentName:MenuDetailMaintenance&selectCode:2308&queryCode:2301&addCode:2302&editCode:2303&deleteCode:2304&idIndex:ID&isRowClick:Y&interfaceTypeDesc:单表操作